package com.kgc.sbt.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created on 2021-05-28.
 * <p>
 * Author: zhukang
 * <p>
 * Description: redis自定义配置类
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
        // 创建一个模板对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();

        // 设置连接工厂对象
        template.setConnectionFactory(factory);

        // 借助fastjson的序列化方式
        FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);

        // 借助String的序列化方式
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key使用string序列化
        template.setKeySerializer(stringRedisSerializer);

        // value使用fastjson序列化
        template.setValueSerializer(fastJsonRedisSerializer);

        // Hash的key也采用String序列化
        template.setHashKeySerializer(stringRedisSerializer);

        // Hash的value也采用fastjson序列化
        template.setHashValueSerializer(fastJsonRedisSerializer);

        // 必须初始化
        template.afterPropertiesSet();

        return template;
    }
}
